package com.fanghuaiming.mtat.sku.config;

import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

/****
 * @description:
 * @version:1.0.0
 * @author fanghuaiming
 * @data Created in 2020/11/28 下午8:44
 *
 */
@Configuration
@MapperScan(basePackages = MtatSkuDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "mtatSkuSqlSessionFactory")
public class MtatSkuDataSourceConfig {

    static final String PACKAGE = "com.fanghuaiming.mtat.sku.dao.mapper";


    /**
     * @Description: 定义dataSource
     *
     * @param:
     * @return:
     * @auther: fanghuaiming
     * @date: 2020/12/1 下午1:30
     * @version:1.0.0
     */
    @Bean(name = "mtatSkuDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.mtat.sku")
    public HikariDataSource mtatSkuDataSource() {
        return new HikariDataSource();
    }

    /**
     * @Description: 定义TransactionManager
     *
     * @param:
     * @return:
     * @auther: fanghuaiming
     * @date: 2020/12/1 下午1:31
     * @version:1.0.0
     */
    @Bean(name = "mtatSkuTransactionManager")
    @Primary
    public DataSourceTransactionManager mtatSkuTransactionManager() {
        return new DataSourceTransactionManager(this.mtatSkuDataSource());
    }

    /**
     * @Description: 定义SqlSessionFactory
     *
     * @param:
     * @return:
     * @auther: fanghuaiming
     * @date: 2020/12/1 下午1:31
     * @version:1.0.0
     */
    @Bean(name = "mtatSkuSqlSessionFactory")
    @Primary
    public SqlSessionFactory mtatSkuSqlSessionFactory(@Qualifier("mtatSkuDataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mappers/*.xml"));
        sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return sessionFactory.getObject();
    }

}
